package com.shiyi.design.singleton;

import java.util.concurrent.TimeUnit;

/**
 * 懒汉式
 * 只有在使用的时候，才会实例化对象，但是有线程安全的问题
 * 可以考虑在方法上加锁，由于是静态方法，锁的是SingletonDesignModel4.class对象
 * 但是效率不高，每次都要获取锁
 *
 * @Author qiu
 * @Date 2021/1/10 23:09
 */
public class SingletonDesignModel4 {
    private static SingletonDesignModel4 INSTANCE;

    private SingletonDesignModel4(){};

    public static synchronized SingletonDesignModel4 getInstance() {
        if(INSTANCE == null) {
            try {
                TimeUnit.SECONDS.sleep(1);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
            INSTANCE = new SingletonDesignModel4();
        }
        return INSTANCE;
    }

    public static void main(String[] args) {
        for (int i = 0; i < 100; i++) {
            new Thread(() -> System.out.println(getInstance().hashCode())).start();
        }
    }
}
